package controller

import (
	"github.com/cn-ygf/go-admin/internal/action"
	"github.com/cn-ygf/go-admin/internal/modular/system/service"
	"github.com/cn-ygf/go-admin/internal/modular/system/vo"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"golang.org/x/crypto/bcrypt"
)

type ProfileController struct {
	Ctx iris.Context
}

// Get 获取用户信息
func (c *ProfileController) Get() mvc.Result {
	user := getCurrentUser(c.Ctx)
	roles, err := service.UserService.GetUserRolesNameByID(user.UserID)
	if err != nil {
		return action.ServerError()
	}
	dept, err := service.DeptService.GetByID(user.DeptID)
	if err != nil {
		return action.ServerError()
	}
	r := &vo.UserProfileRep{
		UserID:      user.UserID,
		DeptID:      user.DeptID,
		DeptName:    dept.DeptName,
		UserName:    user.UserName,
		NickName:    user.NickName,
		UserType:    user.UserType,
		Email:       user.Email,
		Phonenumber: user.Phonenumber,
		Sex:         user.Sex,
		Avatar:      user.Avatar,
		Status:      user.Status,
		Remark:      user.Remark,
		CreatedAt:   user.CreatedAt,
	}
	roleGroup := ""
	for _, item := range roles {
		roleGroup += item + ","
	}
	return action.Data(map[string]any{
		"user":      r,
		"roleGroup": roleGroup[0 : len(roleGroup)-1],
	})
}

func (c *ProfileController) Put(req vo.EditUserProfileReq) mvc.Result {
	user := getCurrentUser(c.Ctx)
	err := service.UserService.UpdateProfile(user.UserID, &req)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	return action.OK()
}

func (c *ProfileController) PutPwd(req vo.UpdateUserPwdReq) mvc.Result {
	user := getCurrentUser(c.Ctx)
	user, err := service.UserService.GetByID(user.UserID)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword))
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.Error("旧密码不正确")
	}

	err = service.UserService.ChangePassword(user.UserID, req.NewPassword)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	return action.OK()
}
